package drds.binlog.parse.inbound.mysql.tsdb.dao;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Statement;


@SuppressWarnings("deprecation")
public class MetaBaseDAO extends SqlMapClientDaoSupport
{


    protected void initTable(String tableName) throws Exception
    {
        Connection connection = null;
        InputStream inputStream = null;
        try
        {
            DataSource dataSource = getDataSource();
            connection = dataSource.getConnection();
            String name = "mysql";

            inputStream = Thread.currentThread()
                    .getContextClassLoader()
                    .getResourceAsStream("ddl/" + name + "/" + tableName + ".sql");
            if (inputStream == null)
            {
                return;
            }

            String sql = StringUtils.join(IOUtils.readLines(inputStream), "\n");
            Statement stmt = connection.createStatement();
            stmt.execute(sql);
            stmt.close();
        } catch (Throwable e)
        {
            logger.warn("init " + tableName + " failed", e);
        } finally
        {
            IOUtils.closeQuietly(inputStream);
            if (connection != null)
            {
                connection.close();
            }
        }
    }


}
